# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

points = np.genfromtxt('data.csv', delimiter=',')
points[0,0]
# 提取两列数据x, y
x = points[:, 0]
y = points[:, 1]
# 使用plt画出散点图
plt.scatter(x, y)
# plt.show()

# 定义损失函数
def conpute_cost(w, b, points):
    total_cost = 0
    M = len(points)
    # 逐个点计算平方损失误差，求平均数
    for i in range(M):
        x = points[i, 0]
        y = points[i, 1]
        total_cost += (y - w * x - b) ** 2
    return total_cost/M

from sklearn.linear_model import LinearRegression
lr = LinearRegression()

new_x = x.reshape(-1, 1)
new_y = y.reshape(-1, 1)
# 画出拟合曲线
lr.fit(new_x, new_y)
# 预测的对应y值
w = lr.coef_[0][0]
b = lr.intercept_[0]
pred_y = w * x + b
plt.plot(x, pred_y, c='r')
plt.show()
